package com.xyongfeng.foodManagement.controller;


import com.xyongfeng.foodManagement.common.BaseResponse;
import com.xyongfeng.foodManagement.common.ErrorCode;
import com.xyongfeng.foodManagement.common.ResultUtils;
import com.xyongfeng.foodManagement.domain.FoodInfo;
import com.xyongfeng.foodManagement.domain.group.AddGroup;
import com.xyongfeng.foodManagement.domain.group.EditGroup;
import com.xyongfeng.foodManagement.domain.group.NormalGroup;
import com.xyongfeng.foodManagement.service.FoodInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 控制食品的接口
 *
 * @author xyongfeng
 */
@RestController
@RequestMapping("/food")
@Slf4j

public class FoodController {

    @Autowired
    private FoodInfoService foodInfoService;
    
    @GetMapping
    public BaseResponse<List<FoodInfo>> selectAll() {
        return ResultUtils.success(foodInfoService.selectAll());
    }
    @RequiresPermissions("food")
    @PostMapping
    public BaseResponse<FoodInfo> insert(@RequestBody @Validated({AddGroup.class, NormalGroup.class}) FoodInfo foodInfo) {
        foodInfo.setFoodStock(0);
        foodInfoService.save(foodInfo);

        return ResultUtils.success(foodInfo);
    }

    @RequiresPermissions("food")
    @DeleteMapping("/{id}")
    public BaseResponse<FoodInfo> deleteById(@PathVariable Long id) {

        FoodInfo foodInfoById = foodInfoService.getById(id);

        boolean b = foodInfoService.removeById(id);
        if (!b) return ResultUtils.error(ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(foodInfoById);
    }
    @RequiresPermissions("food")
    @PutMapping
    public BaseResponse<FoodInfo> updateById(@RequestBody @Validated({EditGroup.class, NormalGroup.class}) FoodInfo foodInfo) {

        boolean foodInfoById = foodInfoService.updateById(foodInfo);
        if (!foodInfoById) return ResultUtils.error(ErrorCode.OPERATION_ERROR.getCode(), "修改失败");
        foodInfo = foodInfoService.getById(foodInfo.getFoodId());

        return ResultUtils.success(foodInfo);
    }

    @GetMapping("/foodNumLt")
    public BaseResponse<List<FoodInfo>> takeQueryFoodNumLt(@RequestParam Integer stock){

        return ResultUtils.success(foodInfoService.takeQueryFoodNumLt(stock));
    }

}
